package cn.mj.netty.serialize;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class ClientUtil {
	
	private static Bootstrap bootstrap = null;
	
	private static ChannelFuture channelFuture = null;
	
	private ClientUtil(){
	}
	
	static{

        EventLoopGroup workerGroup = new NioEventLoopGroup();
        
        bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
        .channel(NioSocketChannel.class)
        .handler(new LoggingHandler(LogLevel.INFO))
        .option(ChannelOption.SO_KEEPALIVE, true);
        
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
            	ch.pipeline().addLast(MarshallingCodeFactory.marshallingDecoder());
            	ch.pipeline().addLast(MarshallingCodeFactory.marshallingEncoder());
                ch.pipeline().addLast(new ClientHandler());
            }
        });
	}
	
	
	public static ChannelFuture getChannelFuture() throws Exception {
		if (channelFuture == null) {
			System.out.println("channelFuture = null");
			channelFuture = bootstrap.connect("127.0.0.1", 8888).sync();
		}else if (!channelFuture.channel().isActive()) {
			System.out.println("channelFuture.isActive = false");
			channelFuture = bootstrap.connect("127.0.0.1", 8888).sync();
		}
		return channelFuture;
	}

}
